package com.mantru.iotpot.dishes

import android.app.Application
import android.util.Log
import android.widget.Toast
import androidx.databinding.ObservableField
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Bean.DishesListShowBean
import com.mantru.iotpot.Util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject

class DishesShowViewModel(application: Application) : AndroidViewModel(application) {

    //实现和activity_dishes.xml的双向绑定
    //菜谱搜索文本框内容
    val dishesSearch = ObservableField<String>("")
    // 数据集合
    val idList = ObservableField<MutableList<String>>()
    val nameList = ObservableField<MutableList<String>>()
    val imageList = ObservableField<MutableList<String>>()
    private val _dishesList = MutableLiveData<MutableList<DishesListShowBean>>()
    val dishesList: LiveData<MutableList<DishesListShowBean>> = _dishesList

    private val applicationClass: ApplicationClass = application as ApplicationClass

    // 初始化viewModel
    init {
        idList.set(mutableListOf())
        nameList.set(mutableListOf())
        imageList.set(mutableListOf())
    }

    // 更新菜品列表数据
    private fun updateDishesList() {
        //确保在主线程进行
        viewModelScope.launch(Dispatchers.Main) {
            val newList = mutableListOf<DishesListShowBean>()
            if (nameList.get()?.isNotEmpty() == true){
                for ( i in 0 until nameList.get()!!.size){
                    newList.add(
                        DishesListShowBean(
                            name = nameList.get()?.get(i).toString(),
                            image = imageList.get()?.get(i).toString(),
                        )
                    )
                }
            }
            _dishesList.postValue(newList)
        }
    }

    //获取网络数据
    fun getHttpValue(api: String, map: Map<String, Any>){
        when ( api ){
            "GetSQLData_Vegetable_Search" ->{//获取搜索菜谱
                val jsonData = applicationClass.GetSQLData_Vegetable_Search(map["type"] as Int, map["data"] as String, map["count"] as Int, map["char"] as String)
                // 处理jsonData为空的情况
                if (!jsonData.isNullOrEmpty()) {
                    try {
                        val jsonObject = JSONObject(jsonData)
                        val success = jsonObject.getBoolean("success")
                        if (success) {
                            idList.get()?.clear()
                            nameList.get()?.clear()
                            imageList.get()?.clear()
                            val itemDataArray = jsonObject.getJSONArray("item_data")
                            if ( itemDataArray.length() > 0 ){
                                for (i in 0 until itemDataArray.length()) {
                                    val jsonItem = itemDataArray.getJSONObject(i)
                                    idList.get()?.add(jsonItem.getString("vegetable_id"))
                                    nameList.get()?.add(jsonItem.getString("vegetable_name"))
                                    imageList.get()?.add(jsonItem.getString("face_image_url"))
                                }
                            }
                            updateDishesList()
                        } else {
                            Log.e("---GetSQLData_Vegetable_List", "API返回success=false")
                        }
                    } catch (e: Exception){
                        Log.e("---GetSQLData_Vegetable_List:",e.toString())
                    }
                    //Toast.makeText(applicationClass, "获取菜谱成功", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(applicationClass, "获取菜谱成功")
                } else {
                    Log.e("---GetSQLData_Vegetable_List", "返回的JSON数据为空")
                }
            }
        }
    }
}